package com.jinshan.service.impl;

import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.jinshan.service.AliyunVideoService;
import com.jinshan.utils.VodUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

@Service
public class AliyunVideoServiceImpl implements AliyunVideoService {
    @Value("${oss.accessKeyId}")
    private String accessKeyId;

     @Value("${oss.accessKeySecret}")
    private String accessKeySecret;

    @Override
    public String uploadVideoToAliyun(MultipartFile file) throws Exception {
        try {
            String filename = file.getOriginalFilename();
            String title = filename.substring(0, filename.lastIndexOf("."));
            InputStream inputStream = file.getInputStream();

            UploadStreamRequest request = new UploadStreamRequest(accessKeyId, accessKeySecret, title, filename, inputStream);
            UploadVideoImpl uploader = new UploadVideoImpl();
            UploadStreamResponse response = uploader.uploadStream(request);
            if (response.isSuccess()) {
                return response.getVideoId();
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
        return null;
    }

    @Override
    public void deleteVideoFromAliyun(String videoId) throws Exception {
        DefaultAcsClient client = VodUtils.initVodClient(accessKeyId, accessKeySecret);
        DeleteVideoRequest deleteVideoRequest = new DeleteVideoRequest();
        deleteVideoRequest.setVideoIds(videoId);
        client.getAcsResponse(deleteVideoRequest);
    }
}
